/**
 * @Creator: eyes
 * @Date: 2019/12/23
 */
import moment from 'moment';
import cloneDeep from 'lodash/cloneDeep';
import {TIME_DURATION} from '~/utils/const';

// 基于moment创建最近一周(不包含今天)的时间区间
export const generateLatestWeek = () => {
    const firstDay = moment()
        .subtract(7, 'day');
    const lastDay = moment()
        .subtract(1, 'day');
    return [firstDay, lastDay];
};

/**
 * 将dateRange[moment, moment]转为服务端需要的['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59']格式.
 * @param startMoment{moment}
 * @param endMoment{moment}
 */
export const calcDateRangeStr = ([startMoment, endMoment] = []) => {
    startMoment.hour(0)
        .minute(0)
        .second(0);
    endMoment.hour(23)
        .minute(59)
        .second(59);
    return [
        startMoment.format('MM-DD HH:mm:ss'),
        endMoment.format('YYYY-MM-DD HH:mm:ss'),
    ];
};

/**
 * 转换成周几
 * @param {String} str  - MM-DD格式的日期
 */
export function parseToWeek(dateStr) {
    if (dateStr.includes('-')) {
        moment.locale('zh-cn');
        const month = dateStr.substring(0, 2) - 1;
        const date = dateStr.substring(3);
        return moment.weekdays()[moment().month(month)
            .date(date)
            .day()];
    }

    return '';
}

// 转曲线图横轴坐标label
/**
 * 转换datetime的格式, 用于折线图横轴上的label显示
 * 比如: YYYY-MM-DD HH:mm:ss ==> MM-DD
 * @param dateStr{String} - YYYY-MM-DD HH:mm:ss格式时间字符串
 * @param duration{Number} - TIME_DURATION常量定义
 */
export const dateFormat = (dateStr, duration) =>
    moment(dateStr, 'YYYY-MM-DD HH:mm:ss')
        .format(duration === TIME_DURATION.MINUTES_10 ? 'HH:mm' : 'MM-DD');

/**
 * 将dateRange[moment, moment]转为服务端需要的['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59']格式.
 * @param startMoment{moment}
 * @param endMoment{moment}
 */
export const getDateRangeStr = ([startMoment, endMoment] = []) => [
    startMoment.startOf('day').format('YYYY-MM-DD HH:mm:ss'),
    endMoment.endOf('day').format('YYYY-MM-DD HH:mm:ss'),
];

/**
 * 将dateRange[moment, moment]转为服务端需要的['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59']格式.
 * @param startMoment{moment}
 * @param endMoment{moment}
 */
export const getWeekRangeStr = ([startMoment, endMoment] = []) => {
    const now = moment().locale('zh-cn')
        .format('YYYY-MM-DD');
    const endTime = endMoment.endOf('isoWeek').format('YYYY-MM-DD');
    // 根据需求，若选择本周,数据则是本周一~昨天的数据
    // 如果按周来选择，并且今天是周一的话，则选择周一到周日的数据，但是结果为空
    if (startMoment.startOf('isoWeek').format('YYYY-MM-DD') === now) {
        endMoment = endMoment.endOf('isoWeek').format('YYYY-MM-DD HH:mm:ss');
    }
    else {
        // 获取周的最后一天和当前时间比较，若周的最后一天大于当前日期，则取当前日期的前一天
        endMoment = moment(endTime).isSameOrAfter(now)
            ? moment().subtract(1, 'day')
                .endOf('day')
                .format('YYYY-MM-DD HH:mm:ss')
            : endMoment.endOf('isoWeek').format('YYYY-MM-DD HH:mm:ss');
    }

    return [
        startMoment.startOf('isoWeek').format('YYYY-MM-DD HH:mm:ss'),
        endMoment
    ];
};

// 定义生成pie所需要的数据的函数
export const generatePieData
    = dataList => dataList.map(item => ({value: item.pv, name: item.field, selected: item.selected}));

/**
 * 当按天查看时 去掉后面小时分 例如： 2020-03-26 00:00:00 => 2020-03-26
 * 当按分钟查看时 增加十分钟 2020-03-26 00:00:00 => 2020-03-26 [00:00 00:10)
*/
export const dateTransfer = (date, type, timestamp = 10 * 60 * 1000) => {
    // 按分钟查看时
    let time;
    if (type >= 10 && type <= 60) {
        time = (new Date(date)).getTime() + timestamp;
        return `${moment(date).format('YYYY-MM-DD')}
                [${moment(date).format('HH:mm')} ${moment(time).format('HH:mm')})`;
    }
    return date.replace(/ (.*)/g, '');
};

export const popUpContainer = triggerNode => triggerNode.parentElement;

/**
 * 用户清单的数据范围限制7天内，若数据范围大于7天，只取7天的数据，否则取用户选取的时间范围
 */
export const generateUserListDateRange = ([startMoment, endMoment] = []) => {
    const temp = moment(endMoment).subtract(6, 'day');
    startMoment = moment(startMoment).isSameOrBefore(temp)
        ? temp
        : startMoment;
    return {
        startTime: startMoment.startOf('day').format('YYYY-MM-DD HH:mm:ss'),
        endTime: endMoment.format('YYYY-MM-DD HH:mm:ss')
    };
};

/**
 *
 */
export const pathTransfer = paths => {
    if (paths.length <= 0) {
        return [];
    }

    const result = [];
    const clonePaths = cloneDeep(paths);
    for (let i = 0, len = clonePaths.length; i < len; i++) {
        const item = [];
        const currentPath = clonePaths[i];
        const nextPath = clonePaths[i + 1];

        // 判断当前path是不是该应用第一个path
        if (i === 0 || (i > 0 && currentPath.bizName !== clonePaths[i - 1].bizName)) {
            currentPath.isFirst = true;
        }
        item.push(currentPath);

        if (nextPath && currentPath.bizName === nextPath.bizName) {
            item.push(nextPath);
            i++;
        }
        result.push(item);
    }

    return result;
};
